package com.shujia.student;

import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class Mapper {
    public static void main(String[] args)throws Exception {


        long start = System.currentTimeMillis();

        /**
         * 线程池
         *
         */
        ExecutorService executorService = Executors.newFixedThreadPool(8);

        /**
         * 每个文件启动一个线程处理
         *
         */

        //获取所有文件
        File pfile = new File("java/data/tmp");

        //获取文件列表
        File[] files = pfile.listFiles();

        for (int i = 0; i < files.length; i++) {
            File file = files[i];
            Test test = new Test(file);
            //启动线程
            executorService.submit(test);
        }

        //关闭先尝尝
        executorService.shutdown();
        //等待关闭
        executorService.awaitTermination(100000L,TimeUnit.SECONDS);

        long end = System.currentTimeMillis();
        System.out.println(end - start);
    }
}

class Test extends Thread {

    private File file;

    public Test(File file) {
        this.file = file;
    }

    @Override
    public void run() {


        /**
         * 统计班级学生的人数
         */

        try {

            FileReader fileReader = new FileReader(file);
            BufferedReader bufferedReader = new BufferedReader(fileReader);
            HashMap<String, Long> map = new HashMap<>();

            String line;
            while ((line = bufferedReader.readLine()) != null) {
                String clazz = line.split(",")[4];

                Long aLong = map.get(clazz);
                if (aLong != null) {
                    map.put(clazz, aLong + 1);
                } else {
                    map.put(clazz, 1L);
                }

            }

            System.out.println(map);
            bufferedReader.close();
            fileReader.close();


            //将初步统计的结果保存到文件
            String path = "java/data/tmp2/" + file.getName();
            FileWriter fileWriter = new FileWriter(path);
            BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);


            for (Map.Entry<String, Long> entry : map.entrySet()) {
                String key = entry.getKey();
                Long value = entry.getValue();

                String kv = key + "," + value;

                bufferedWriter.write(kv);
                bufferedWriter.newLine();
            }

            bufferedWriter.close();
            fileWriter.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
